package com.sgd.cli.example;

import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 *
 * @author su.gd
 * @date 2023-11-21
 */
@Command
public class Main implements Runnable{

    @Option(names = {"-v", "--value"}, arity = "0..1", interactive = true)
    String value;

    @Override
    public void run() {
        System.out.println("value: " + value);
    }

    public static void main(String[] args) {
        // 用来接收/继续添加命令参数
        String[] newArgs = args;
        Class<Main> clazz = Main.class;
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            Option optionAnnotation = field.getAnnotation(Option.class);
            // 判断是否是交互式选项
            boolean interactive = optionAnnotation.interactive();
            if (interactive) {
                // 获取 names 属性值
                String[] names = optionAnnotation.names();
                // 是否存在交互式选项
                boolean exist = Arrays.stream(names).anyMatch(name -> Arrays.binarySearch(args, name) >= 0);
                // 如果用户输入的命令中没有交互式选项，那么就自动为输入命令补充该选项，从而可以强制触发交互式输入
                if (!exist) {
                    newArgs = new String[args.length + 1];
                    System.arraycopy(args, 0, newArgs, 0, args.length);
                    newArgs[args.length] = names[0];
                }
            }
        }

        new CommandLine(new Main()).execute(newArgs);
    }
}
